<script setup lang="ts">
import { ref, onMounted, reactive, computed, onBeforeUnmount } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  ToolboxComponent,
} from 'echarts/components'
import * as echarts from 'echarts/core'
import { getLandslideStatistics } from '@/services/statisticsService'
import { ElMessage } from 'element-plus'

// 注册 ECharts 必需的组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  ToolboxComponent,
])

// 页面动画效果
const pageClass = ref('')

// 图表容器引用
const timeDistributionChartRef = ref<HTMLDivElement>()
const areaDistributionChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()
const severityChartRef = ref<HTMLDivElement>()

// 图表实例
let timeDistributionChart: echarts.ECharts | null = null
let areaDistributionChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let severityChart: echarts.ECharts | null = null

// 统计数据
const statistics = reactive({
  totalCount: 0,
  recentCount: 0,
  highRiskCount: 0,
  areaData: [] as { name: string; value: number }[],
  timeData: [] as { name: string; value: number }[],
  trendData: [] as { month: string; count: number }[],
  severityData: [] as { name: string; value: number }[],
})

// 加载状态
const loading = ref(true)

// 计算属性：获取当前年份
const currentYear = computed(() => new Date().getFullYear())

/**
 * 获取指定风险等级的滑坡数量
 * @param riskLevel 风险等级
 * @returns 该风险等级的滑坡数量
 */
function getRiskLevelCount(riskLevel: string): number {
  const item = statistics.severityData.find((item) => item.name === riskLevel)
  return item ? item.value : 0
}

/**
 * 获取时间分布分析结论
 * @returns 时间分布分析结论
 */
function getTimeAnalysis(): string {
  // 获取最大值和对应的年份
  let maxYear = ''
  let maxValue = 0

  statistics.timeData.forEach((item) => {
    if (item.value > maxValue) {
      maxValue = item.value
      maxYear = item.name
    }
  })

  // 计算增长趋势
  const sortedData = [...statistics.timeData].sort((a, b) => {
    const yearA = parseInt(a.name.replace('年', ''))
    const yearB = parseInt(b.name.replace('年', ''))
    return yearA - yearB
  })

  const isIncreasing =
    sortedData.length >= 2 &&
    sortedData[sortedData.length - 1].value > sortedData[sortedData.length - 2].value

  // 特别处理2025年的数据
  const year2025Data = statistics.timeData.find((item) => item.name === '2025年')
  const year2025Value = year2025Data ? year2025Data.value : 0

  if (maxYear === '2025年' && year2025Value > 0) {
    return `2025年已记录${year2025Value}起滑坡事件，是近年来滑坡事件的高发期，需要重点关注。`
  } else {
    return `近年来滑坡事件${isIncreasing ? '呈现逐年增加趋势' : '数量有所波动'}，${maxYear}记录的滑坡事件数量为${maxValue}起，${isIncreasing ? '明显高于往年同期' : '是历史高发期之一'}。`
  }
}

/**
 * 获取区域分布分析结论
 * @returns 区域分布分析结论
 */
function getAreaAnalysis(): string {
  // 获取前两个高发区域
  const sortedAreas = [...statistics.areaData].sort((a, b) => b.value - a.value)

  // 过滤掉数量为0的区域
  const validAreas = sortedAreas.filter((area) => area.value > 0)

  // 如果没有有效数据，返回默认文本
  if (validAreas.length === 0) {
    return '目前尚未收集到足够的区域分布数据，请继续录入滑坡事件信息。'
  }

  // 获取前两个高发区域
  const topAreas = validAreas.slice(0, Math.min(2, validAreas.length))

  // 计算这些区域占总数的百分比
  const totalCount = statistics.totalCount || 1 // 避免除以0
  const topAreasCount = topAreas.reduce((sum, item) => sum + item.value, 0)
  const percentage = Math.round((topAreasCount / totalCount) * 100)

  if (topAreas.length === 1) {
    return `${topAreas[0].name}是滑坡事件高发区域，占全市滑坡事件总数的${percentage}%。`
  } else {
    return `${topAreas.map((a) => a.name).join('和')}是滑坡事件高发区域，占全市滑坡事件总数的${percentage}%以上。`
  }
}

/**
 * 获取风险等级分析结论
 * @returns 风险等级分析结论
 */
function getRiskLevelAnalysis(): string {
  const totalCount = statistics.totalCount || 1 // 避免除以0
  const highRiskCount = getRiskLevelCount('高风险')
  const extremeRiskCount = getRiskLevelCount('极高风险')

  const highRiskPercentage = Math.round((highRiskCount / totalCount) * 100)
  const extremeRiskPercentage = Math.round((extremeRiskCount / totalCount) * 100)

  return `全市约有${highRiskPercentage}%的滑坡点位于高风险区域，${extremeRiskPercentage}%位于极高风险区域，需重点关注。`
}

/**
 * 获取趋势预测分析结论
 * @returns 趋势预测分析结论
 */
function getTrendAnalysis(): string {
  // 找出高发月份（值最大的三个月）
  const sortedMonths = [...statistics.trendData].sort((a, b) => b.count - a.count)
  const topMonths = sortedMonths.filter((m) => m.count > 0).slice(0, 3)

  // 如果没有数据，返回默认文本
  if (topMonths.length === 0) {
    return `根据历史数据分析，雨季（6-8月）通常是滑坡事件的高发期，建议提前做好防范工作。`
  }

  // 将月份转换为数字
  const monthNumbers = topMonths.map((item) => parseInt(item.month))

  // 判断是否集中在雨季（6-8月）
  const isRainySeason = monthNumbers.some((m) => m >= 6 && m <= 8)

  return `根据2025年数据分析，${topMonths.map((m) => m.month).join('、')}是滑坡事件的高发期，${isRainySeason ? '与雨季相吻合，' : ''}建议提前做好防范工作。`
}

/**
 * 初始化图表
 */
function initCharts() {
  // 初始化时间分布图表
  if (timeDistributionChartRef.value) {
    timeDistributionChart = echarts.init(timeDistributionChartRef.value)
    const timeOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#b71c1c',
        },
      },
      series: [
        {
          name: '时间分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: statistics.timeData,
        },
      ],
      color: ['#ffb74d', '#ff9800', '#f57c00', '#e65100', '#bf360c'],
    }
    timeDistributionChart.setOption(timeOption)
  }

  // 初始化区域分布图表
  if (areaDistributionChartRef.value) {
    areaDistributionChart = echarts.init(areaDistributionChartRef.value)
    const areaOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
        axisLabel: {
          color: '#b71c1c',
        },
      },
      yAxis: {
        type: 'category',
        data: statistics.areaData.map((item) => item.name),
        axisLabel: {
          color: '#b71c1c',
        },
      },
      series: [
        {
          name: '事件数量',
          type: 'bar',
          data: statistics.areaData.map((item) => item.value),
        },
      ],
      color: ['#ff9800'],
    }
    areaDistributionChart.setOption(areaOption)
  }

  // 初始化趋势图表
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: statistics.trendData.map((item) => item.month),
        axisLabel: {
          color: '#b71c1c',
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#b71c1c',
        },
      },
      series: [
        {
          data: statistics.trendData.map((item) => item.count),
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
          },
          itemStyle: {
            borderWidth: 2,
          },
        },
      ],
      color: ['#e65100'],
    }
    trendChart.setOption(trendOption)
  }

  // 初始化严重程度图表
  if (severityChartRef.value) {
    severityChart = echarts.init(severityChartRef.value)
    const severityOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#b71c1c',
        },
      },
      series: [
        {
          name: '风险等级',
          type: 'pie',
          radius: '50%',
          data: statistics.severityData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
      color: ['#4caf50', '#ffeb3b', '#ff9800', '#f44336'],
    }
    severityChart.setOption(severityOption)
  }
}

/**
 * 处理窗口大小变化，调整图表大小
 */
function handleResize() {
  timeDistributionChart?.resize()
  areaDistributionChart?.resize()
  trendChart?.resize()
  severityChart?.resize()
}

/**
 * 加载滑坡数据并生成统计信息
 */
async function loadStatistics() {
  try {
    loading.value = true

    // 获取统计数据
    const data = await getLandslideStatistics()

    // 更新统计数据
    statistics.totalCount = data.totalCount
    statistics.recentCount = data.recentCount
    statistics.highRiskCount = data.highRiskCount
    statistics.areaData = data.areaData
    statistics.timeData = data.timeData
    statistics.trendData = data.trendData
    statistics.severityData = data.severityData

    // 初始化图表
    initCharts()

    loading.value = false
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('统计数据加载失败')
    loading.value = false
  }
}

onMounted(() => {
  // 添加进入动画类
  setTimeout(() => {
    pageClass.value = 'page-show'
  }, 100)

  // 加载统计数据
  loadStatistics()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  timeDistributionChart?.dispose()
  areaDistributionChart?.dispose()
  trendChart?.dispose()
  severityChart?.dispose()

  timeDistributionChart = null
  areaDistributionChart = null
  trendChart = null
  severityChart = null
})
</script>

<template>
  <div class="statistics-page" :class="pageClass">
    <!-- 页面标题 - 简化版 -->
    <div class="page-title">
      <h2>滑坡风险统计分析</h2>
    </div>

    <!-- 统计卡片区域 - 简化版，类似截图样式 -->
    <div class="statistics-summary">
      <div class="summary-header">
        <span>数据可视化 · 趋势分析 · 风险评估</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="summary-card">
            <div class="card-icon orange">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-label">滑坡总数</div>
              <div class="card-value orange">{{ statistics.totalCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-card">
            <div class="card-icon blue">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-label">近期滑坡</div>
              <div class="card-value blue">{{ statistics.recentCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-card">
            <div class="card-icon red">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-label">高风险区域</div>
              <div class="card-value red">{{ statistics.highRiskCount }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 风险等级详细统计 -->
      <div class="risk-level-details">
        <div class="risk-level-title">风险等级详细统计</div>
        <div class="risk-level-tags">
          <el-tag type="success" effect="plain" class="risk-tag">
            低风险: {{ getRiskLevelCount('低风险') }}
          </el-tag>
          <el-tag type="warning" effect="plain" class="risk-tag">
            中风险: {{ getRiskLevelCount('中风险') }}
          </el-tag>
          <el-tag type="danger" effect="plain" class="risk-tag">
            高风险: {{ getRiskLevelCount('高风险') }}
          </el-tag>
          <el-tag type="danger" effect="plain" class="risk-tag">
            极高风险: {{ getRiskLevelCount('极高风险') }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-box">
            <div class="chart-title">滑坡事件时间分布</div>
            <div class="chart" ref="timeDistributionChartRef"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-box">
            <div class="chart-title">滑坡事件区域分布</div>
            <div class="chart" ref="areaDistributionChartRef"></div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="12">
          <div class="chart-box">
            <div class="chart-title">{{ currentYear }}年滑坡事件趋势</div>
            <div class="chart" ref="trendChartRef"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-box">
            <div class="chart-title">滑坡风险等级分布</div>
            <div class="chart" ref="severityChartRef"></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 分析结论区域 -->
    <div class="analysis-box">
      <div class="analysis-title">分析结论</div>
      <div class="analysis-content">
        <p>
          <strong>时间分布分析：</strong>
          {{ getTimeAnalysis() }}
        </p>
        <p>
          <strong>区域分布分析：</strong>
          {{ getAreaAnalysis() }}
        </p>
        <p>
          <strong>风险等级分析：</strong>
          {{ getRiskLevelAnalysis() }}
        </p>
        <p>
          <strong>趋势预测：</strong>
          {{ getTrendAnalysis() }}
        </p>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <el-loading :visible="loading" fullscreen element-loading-text="数据加载中..." />
  </div>
</template>

<style lang="scss" scoped>
.statistics-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s ease;
}

.page-show {
  opacity: 1;
  transform: translateY(0);
}

.page-title {
  margin-bottom: 20px;

  h2 {
    color: #b71c1c;
    font-size: 20px;
    font-weight: 500;
    margin: 0;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
  }
}

.statistics-summary {
  margin-bottom: 30px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .summary-header {
    text-align: center;
    padding-bottom: 15px;
    margin-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;

    span {
      color: #666;
      font-size: 14px;
    }
  }

  .summary-card {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;

    .card-icon {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      margin-right: 15px;

      .el-icon {
        font-size: 20px;
        color: white;
      }

      &.orange {
        background-color: #ff9800;
      }

      &.blue {
        background-color: #2196f3;
      }

      &.red {
        background-color: #f44336;
      }
    }

    .card-content {
      flex: 1;

      .card-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;

        &.orange {
          color: #ff9800;
        }

        &.blue {
          color: #2196f3;
        }

        &.red {
          color: #f44336;
        }
      }
    }
  }

  .risk-level-details {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px dashed #eee;

    .risk-level-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 10px;
      text-align: center;
    }

    .risk-level-tags {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;

      .risk-tag {
        margin: 5px;
        padding: 6px 12px;
        font-size: 13px;
      }
    }
  }
}

.chart-container {
  margin-bottom: 30px;

  .chart-box {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 15px;
    margin-bottom: 20px;

    .chart-title {
      font-size: 16px;
      color: #333;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    .chart {
      height: 300px;
      width: 100%;
    }
  }
}

.analysis-box {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .analysis-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .analysis-content {
    p {
      margin-bottom: 10px;
      line-height: 1.6;

      &:last-child {
        margin-bottom: 0;
      }

      strong {
        color: #e65100;
      }
    }
  }
}
</style>
